from flask import Blueprint, request, jsonify
from app import db, jwt
from app.models.daily_activity import DailyActivity
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime

bp = Blueprint('daily_activity', __name__, url_prefix='/api/daily-activity')

@bp.route('', methods=['POST'])
@jwt_required()
def create_daily_activity():
    """创建日常活动记录"""
    try:
        user_id = get_jwt_identity()
        data = request.get_json()
        
        # 处理日期字段 - 将字符串转换为datetime对象
        record_date_str = data.get('record_date')
        record_date = None
        if record_date_str:
            try:
                # 将日期字符串转换为datetime对象
                record_date = datetime.strptime(record_date_str, '%Y-%m-%d')
            except ValueError:
                return jsonify({'error': '日期格式错误，请使用 YYYY-MM-DD 格式'}), 400
        else:
            record_date = datetime.utcnow()
        
        daily_activity = DailyActivity(
            user_id=user_id,
            record_date=record_date,
            steps=data.get('steps'),
            exercise_minutes=data.get('exercise_minutes'),
            calories_burned=data.get('calories_burned'),
            sleep_hours=data.get('sleep_hours'),
            sleep_quality=data.get('sleep_quality'),
            water_intake=data.get('water_intake'),
            notes=data.get('notes')
        )
        
        db.session.add(daily_activity)
        db.session.commit()
        
        return jsonify({
            'message': '日常活动记录创建成功',
            'data': daily_activity.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@bp.route('', methods=['GET'])
@jwt_required()
def get_daily_activities():
    """获取用户的全部日常活动记录"""
    try:
        user_id = get_jwt_identity()
        records = DailyActivity.query.filter_by(user_id=user_id).order_by(DailyActivity.record_date.desc()).all()
        
        return jsonify({
            'data': [record.to_dict() for record in records]
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@bp.route('/<int:record_id>', methods=['GET'])
@jwt_required()
def get_daily_activity_by_id(record_id):
    """获取特定日常活动记录"""
    try:
        user_id = get_jwt_identity()
        record = DailyActivity.query.filter_by(id=record_id, user_id=user_id).first()
        
        if not record:
            return jsonify({'error': '记录不存在'}), 404
            
        return jsonify({
            'data': record.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@bp.route('/<int:record_id>', methods=['PUT'])
@jwt_required()
def update_daily_activity(record_id):
    """更新日常活动记录"""
    try:
        user_id = get_jwt_identity()
        record = DailyActivity.query.filter_by(id=record_id, user_id=user_id).first()
        
        if not record:
            return jsonify({'error': '记录不存在'}), 404
        
        data = request.get_json()
        
        # 处理日期字段
        if 'record_date' in data and data['record_date']:
            try:
                record.record_date = datetime.strptime(data['record_date'], '%Y-%m-%d')
            except ValueError:
                return jsonify({'error': '日期格式错误，请使用 YYYY-MM-DD 格式'}), 400
        
        # 更新其他字段
        update_fields = [
            'steps', 'exercise_minutes', 'calories_burned',
            'sleep_hours', 'sleep_quality', 'water_intake', 'notes'
        ]
        
        for field in update_fields:
            if field in data:
                setattr(record, field, data[field])
        
        db.session.commit()
        
        return jsonify({
            'message': '日常活动记录更新成功',
            'data': record.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@bp.route('/<int:record_id>', methods=['DELETE'])
@jwt_required()
def delete_daily_activity(record_id):
    """删除日常活动记录"""
    try:
        user_id = get_jwt_identity()
        record = DailyActivity.query.filter_by(id=record_id, user_id=user_id).first()
        
        if not record:
            return jsonify({'error': '记录不存在'}), 404
        
        db.session.delete(record)
        db.session.commit()
        
        return jsonify({
            'message': '日常活动记录删除成功'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500